<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Shop\Controller;

use Admin\Data\Common;
use Doctrine\ORM\EntityManager;
use Laminas\Mvc\I18n\Translator;
use Laminas\View\Model\JsonModel;
use Laminas\View\Model\ViewModel;
use Shop\Form\UserAddressForm;
use User\Entity\UserAddress;
use User\Service\UserAddressManager;

class HomeUserAddressController extends HomeActionController
{
    private $translator;
    private $writeEntityManager;
    private $userAddressManager;

    public function __construct(
        Translator      $translator,
        EntityManager   $writeEntityManager,
        UserAddressManager $userAddressManager
    )
    {
        $this->translator           = $translator;
        $this->writeEntityManager   = $writeEntityManager;
        $this->userAddressManager   = $userAddressManager;
    }

    /**
     * 收货地址列表
     * @return array|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        $this->layout()->setVariable('titleName', $this->translator->translate('地址管理'));

        $userAddressList = $this->writeEntityManager->getRepository(UserAddress::class)->findBy(['userId' => parent::$userId]);

        return [
            'userAddressList'   => $userAddressList,
            'phoneAreaCode'     => Common::configValue('list', 'phoneArea'),
        ];
    }

    /**
     * 收货地址，添加与更新
     * @return array|ViewModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function userAddressAction()
    {
        $addressId = (int) $this->params()->fromQuery('addressId', 0);

        $addressInfo = null;
        if($addressId > 0) {
            $addressInfo = $this->writeEntityManager->getRepository(UserAddress::class)->findOneBy(['addressId' => $addressId, 'userId' => parent::$userId]);
            if($addressInfo == null) $addressId = 0;
        }

        $status     = false;
        $phoneArea  = Common::getPhoneArea();
        $form       = new UserAddressForm($phoneArea);
        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();
                $data['userId'] = parent::$userId;
                if($addressId > 0) $userAddress = $this->userAddressManager->editUserAddress($data, $addressInfo, $addressId);
                else {
                    $userAddress = $this->userAddressManager->addUserAddress($data);
                }

                $status = true;
                if($userAddress) $this->flashMessenger()->addSuccessMessage(sprintf($this->translator->translate('收货地址%s完成!'), ($addressId > 0 ? $this->translator->translate('编辑') : $this->translator->translate('添加'))));
                else $this->flashMessenger()->addWarningMessage(sprintf($this->translator->translate('收货地址%s失败!'), ($addressId > 0 ? $this->translator->translate('编辑') : $this->translator->translate('添加'))));
            }
        }

        if($addressId > 0) $form->setData($addressInfo->valuesArray());

        if (Common::isMobile()) return ['status' => $status, 'addressInfo' => $addressInfo, 'form' => $form, 'phoneArea' => $phoneArea, 'region' => $this->shopPlugin()->getRegionSub()];
        else {
            $view = new ViewModel();
            $view->setTerminal(true);
            return $view->setVariables(['status' => $status, 'addressInfo' => $addressInfo, 'form' => $form, 'phoneArea' => $phoneArea, 'region' => $this->shopPlugin()->getRegionSub()]);
        }
    }

    /**
     * 收货地址删除
     * @return JsonModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteUserAddressAction()
    {
        $addressId = $this->params()->fromRoute('id', -1);

        $addressInfo = $this->writeEntityManager->getRepository(UserAddress::class)->findOneBy(['userId' => parent::$userId, 'addressId' => $addressId]);
        if($addressInfo == null) return new JsonModel(['status' => 'false', 'message' => $this->translator->translate('该收货地址不存在!')]);

        if($this->userAddressManager->deleteUserAddress($addressInfo)) return new JsonModel(['status' => 'true']);

        return new JsonModel(['status' => 'false', 'message' => $this->translator->translate('收货地址删除失败!')]);
    }
}